﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Data.Services.Client;
using System.Threading;
using System.Xml.Linq;
using System.Threading.Tasks;

namespace CloudTrace
{
    public class TableTraceListener : CloudTraceListener
    {
        private CloudTable table;
        private string tableName;

        #region ctor
        public TableTraceListener(string initializeData)
            : base(initializeData)
        {
        }

        #endregion

        protected override void SaveMessage(LogMessage logMessage)
        {
            if (null == table)
                this.InitializeService();

            LogMessageEntity tableMessage = new LogMessageEntity(logMessage);
            tableMessage.SetProperties();

            TableOperation insertOperation = TableOperation.Insert(tableMessage);

            if (this.async)
            {
                Task<TableResult> task = Task<TableResult>.Factory.FromAsync(table.BeginExecute, table.EndExecute, insertOperation, null);
                this.tasks.Add(task);
                task.ContinueWith(t => tasks.Remove(t));
            }
            else
            {
                table.Execute(insertOperation);
            }
        }

        #region private helpers
        protected override void InitializeService()
        {
            base.Initialize();

            tableName = Attributes[SupportedAttributes.tableName.ToString()] ??
                settings[SupportedAttributes.tableName.ToString()] ?? "TableTraceListener";

            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            table = tableClient.GetTableReference(tableName);
            table.CreateIfNotExists();
        }
        #endregion

    }
}
